package com.ruoyi.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.web.domain.mes.*;
import com.ruoyi.web.mapper.MesOrderMapper;
import com.ruoyi.web.utils.UtilsSetting;
import com.ruoyi.web.vo.Produce;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MesOrderService extends ServiceImpl<MesOrderMapper, MesOrder> {
    @Resource
    private MesOrderMapper mesOrderMapper;
    @Resource
    private Validator validator;
    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Resource
    private MesOrderCoverService mesOrderCoverService;

    @Resource
    private MesOrderBreedService  mesOrderBreedService;
    @Resource
    private ProduceService produceService;

    /**
     * 订单管理 -- 查询
     * @Date: 2024年1月9日
     * @Auth: 张恒
     */
    public TableDataInfo getMesOrderInfo(MesOrder mesOrder){
        PageHelper.startPage(mesOrder.getPageNum(), mesOrder.getPageSize());
        List<MesOrder> mesOrders = new ArrayList<>();
        if(StringUtils.isNotBlank(mesOrder.getDataType())){
            mesOrders = mesOrderMapper.selectMesOrderMakeUp(mesOrder);
        }else {
            mesOrders = mesOrderMapper.selectMesOrder(mesOrder);
        }

        for (MesOrder Order: mesOrders){
            List<MesOrderCover> mesOrderCovers= mesOrderCoverService.list(new QueryWrapper<MesOrderCover>()
                    .lambda().eq(MesOrderCover::getOrderId,
                            Order.getPid()));
            Order.setOrderCover(mesOrderCovers);
            // 实时查询印刷次数：只查内文
            List<Produce> list = produceService.list(new QueryWrapper<Produce>()
                    .eq("type", "2") // 1.封面生产单 2.内文生产单
                    .eq("order_id", Order.getPid())
                    .ne("status", "0") // 0作废
            );
            Order.setPrintNum(list.size());
        }
        PageInfo pageInfo = new PageInfo<>(mesOrders);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setTotal(pageInfo.getTotal());
        tableDataInfo.setRows(pageInfo.getList());
        return tableDataInfo;
    }

    /**
     * 订单管理 -- 查询明细
     * @Date: 2024年1月9日
     * @Auth: 张恒
     */
    public AjaxResult getMesOrderDetail(MesOrder mesOrder){
        if(mesOrder.getPid() == null){
            return AjaxResult.error("未获取到主要信息");
        }
        // 查询主表信息
        List<MesOrder> orders = mesOrderMapper.selectMesOrder(mesOrder);
        MesOrder mesOrder1 = orders.get(0);
        // 查询品种信息
        MesOrderBreed orderBreed = new MesOrderBreed();
        orderBreed.setOrderId(mesOrder.getPid());
        if(StringUtils.isNotBlank(mesOrder.getPrintCategory())){
            orderBreed.setPrintCategory(mesOrder.getPrintCategory());
        }
        List<MesOrderBreed> mesOrderBreeds = mesOrderMapper.selectMesOrderBreed(orderBreed);
        if(mesOrderBreeds.size() > 0){
            ArrayList<String> longs = new ArrayList<>();
            mesOrderBreeds.forEach(e -> {
                longs.add(e.getPid());
            });
            mesOrder1.setOrderBreed(mesOrderBreeds);
            // 获取产品信息
            MesOrderProduct orderProduct = new MesOrderProduct();
            orderProduct.setBreedPidList(longs);
            orderProduct.setIsUsed(mesOrder.getIsUsed());
            List<MesOrderProduct> mesOrderProducts = mesOrderMapper.selectMesOrderProduct(orderProduct);
            mesOrder1.setOrderProduct(mesOrderProducts);
            // 获取内文信息
            MesOrderNeiwen orderNeiwen = new MesOrderNeiwen();
            orderNeiwen.setBreedPidList(longs);
            List<MesOrderNeiwen> mesOrderNeiwens = mesOrderMapper.selectMesOrderNeiwen(orderNeiwen);
            mesOrder1.setOrderNeiwen(mesOrderNeiwens);
        }

       List<MesOrderCover> mesOrderCovers= mesOrderCoverService.list(new QueryWrapper<MesOrderCover>()
               .lambda().eq(MesOrderCover::getOrderId,
                        mesOrder1.getPid()).orderByAsc(MesOrderCover::getSort));
        mesOrder1.setOrderCover(mesOrderCovers);
        return AjaxResult.success(mesOrder1);
    }


    /**
     * 订单管理 -- 新增
     * @Date: 2024年1月9日
     * @Auth: 张恒
     */
    @Transactional
    public AjaxResult addMesOrderInfo(MesOrder mesOrder){
        String username = SecurityUtils.getUsername();
        Date date = new Date();
        mesOrder.setCreateBy(username);
        mesOrder.setCreateTime(date);
        // 查询当月的数据
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        MesOrder order1 = new MesOrder();
        order1.setYearTime(year);
        order1.setMonthTime(month);
        List<MesOrder> orders = mesOrderMapper.selectMesOrder(order1);
        // 获取最大的序号
        Integer maxNum = 1;
        if(orders.size() > 0){
            for (MesOrder mesOrder1 : orders) {
                if(maxNum.compareTo(mesOrder1.getCodeNum()) < 0){
                    maxNum = mesOrder1.getCodeNum();
                }
            }
        }
        maxNum = maxNum + 1;
        // 获取编码
        String code = UtilsSetting.getCode(maxNum, "DD", date);
        mesOrder.setOrderNo(code);
        // 校验订单数据
        BeanValidators.validateWithException(validator, mesOrder);
        // 保存品种信息
        Map<String, MesOrderBreed> breedMap = null;
        // 处理品种信息
        if(mesOrder.getOrderBreed() != null && mesOrder.getOrderBreed().size() > 0){
            List<MesOrderBreed> mesOrderBreed = mesOrder.getOrderBreed();
            mesOrderBreed.forEach(e ->{
                BeanValidators.validateWithException(validator, e);
            });
            breedMap = mesOrderBreed.stream().collect(Collectors.toMap(MesOrderBreed::getPid, e -> e));
        }
        // 保存之前先校验书刊编码是否重复
        MesOrder order = new MesOrder();
        order.setBookCode(mesOrder.getBookCode());
        List<MesOrder> mesOrders1 = mesOrderMapper.selectBookCode(order);

//        List<MesOrder> mesOrders = mesOrders1.stream().filter(it -> it.getStatus().equals(0))
//                .collect(Collectors.toList());
        if(mesOrders1!=null && mesOrders1.size() >0){
            return AjaxResult.error("书刊编码已存在，请修改后保存");
        }

        // 保存之前先校验出版编码是否重复
//        MesOrder pubno = new MesOrder();
//        pubno.setPubNo(mesOrder.getPubNo());
//        List<MesOrder> mesOrders2 = mesOrderMapper.selectPubNo(pubno);
//        if(mesOrders2!=null && mesOrders2.size()>0){
//            return AjaxResult.error("出版编码已存在，请重新生成");
//        }

        // 保存订单信息
        mesOrderMapper.insertMesOrder(mesOrder);

        for (MesOrderCover mesOrderCover: mesOrder.getOrderCover()){
            mesOrderCover.setOrderId(String.valueOf(mesOrder.getPid()));
        }
        mesOrderCoverService.saveBatch(mesOrder.getOrderCover());
        // 处理子信息
        if(breedMap != null){
            // 获取品种最大编码
            MesOrderBreed breed = new MesOrderBreed();
            breed.setYearTime(year);
            breed.setMonthTime(month);
            List<MesOrderBreed> mesOrderBreeds = mesOrderMapper.selectMesOrderBreed(breed);
            // 获取最大的序号
            Integer maxBreen = 1;
            if(mesOrderBreeds.size() > 0){
                for (MesOrderBreed orderBreed : mesOrderBreeds) {
                    if(maxBreen.compareTo(orderBreed.getCodeNum()) < 0){
                        maxBreen = orderBreed.getCodeNum();
                    }
                }
            }
            maxBreen = maxBreen + 1;

            for (String breedId : breedMap.keySet()) {
                // 获取品种编码
                String codeBreen = UtilsSetting.getCode(maxBreen, "DDPZ", date);
                // 获取品种信息
                MesOrderBreed orderBreed = breedMap.get(breedId);
                orderBreed.setBreedNo(codeBreen);
                orderBreed.setOrderId(mesOrder.getPid());
                orderBreed.setCreateBy(username);
                orderBreed.setCreateTime(date);
                // 新增品种信息
                mesOrderMapper.insertMesOrderBreed(orderBreed);
                maxBreen ++;
           }
        }
        return AjaxResult.success();
    }

    /**
     * 订单管理 -- 修改
     * @Date: 2024年1月9日
     * @Auth: 张恒
     */
    @Transactional
    public AjaxResult editMesOrderInfo(MesOrder mesOrder){
        if(mesOrder.getPid() == null){
            return AjaxResult.error("未获取到修改的主键");
        }
        String username = SecurityUtils.getUsername();
        Date date = new Date();
        mesOrder.setUpdateBy(username);
        mesOrder.setUpdateTime(date);
        // 查询修改的数据
        MesOrder order = new MesOrder();
        order.setPid(mesOrder.getPid());
        List<MesOrder> mesOrders = mesOrderMapper.selectMesOrder(order);
        // 判断状态
        if(mesOrders.get(0).getStatus() != 1){
            return AjaxResult.error("只有未提交的订单才可编辑");
        }
        // 查询当月的数据
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;

        // 保存品种信息
        Map<String, MesOrderBreed> breedMapAdd = null;
       List<MesOrderBreed>  orderBreedEdit = new ArrayList<>();
        Map<String,MesOrderBreed>  breedEdit=null;
        // 处理品种信息
        if(mesOrder.getOrderBreed() != null && mesOrder.getOrderBreed().size() > 0){
            List<MesOrderBreed> mesOrderBreed = mesOrder.getOrderBreed();
            mesOrderBreed.forEach(e ->{
                BeanValidators.validateWithException(validator, e);
            });
            // 根据类型 type 分组：1新增，2修改
            Map<Integer, List<MesOrderBreed>> listMap = mesOrderBreed.stream().collect(Collectors.groupingBy(MesOrderBreed::getType));
            List<MesOrderBreed> mesOrderBreedAdd =listMap.get(1);
            if(mesOrderBreedAdd != null && mesOrderBreedAdd.size() > 0){
                breedMapAdd = mesOrderBreedAdd.stream().collect(Collectors.toMap(MesOrderBreed::getPid, e -> e));
            }
             orderBreedEdit = listMap.get(2);
            if(orderBreedEdit != null && orderBreedEdit.size() > 0){
                breedEdit = orderBreedEdit.stream().collect(Collectors.toMap(MesOrderBreed::getPid, e -> e));
            }

        }
        if(breedEdit != null) {
            mesOrderBreedService.remove(new QueryWrapper<MesOrderBreed>().lambda()
                    .eq(MesOrderBreed::getOrderId, mesOrder.getPid()));
            // 获取品种最大编码
            MesOrderBreed breed = new MesOrderBreed();
            breed.setYearTime(year);
            breed.setMonthTime(month);
            List<MesOrderBreed> mesOrderBreeds = mesOrderMapper.selectMesOrderBreed(breed);
            // 获取最大的序号
            Integer maxBreen = 1;
            if (mesOrderBreeds.size() > 0) {
                for (MesOrderBreed orderBreed : mesOrderBreeds) {
                    if (maxBreen.compareTo(orderBreed.getCodeNum()) < 0) {
                        maxBreen = orderBreed.getCodeNum();
                    }
                }
            }
            maxBreen = maxBreen + 1;

            for (String breedId : breedEdit.keySet()) {
                // 获取品种编码
                String codeBreen = UtilsSetting.getCode(maxBreen, "DDPZ", date);
                // 获取品种信息
                MesOrderBreed orderBreed = breedEdit.get(breedId);
                orderBreed.setOrderId(mesOrder.getPid());
                orderBreed.setBreedNo(codeBreen);
                orderBreed.setCreateBy(username);
                orderBreed.setCreateTime(date);
                // 新增品种信息
                mesOrderMapper.insertMesOrderBreed(orderBreed);
                maxBreen++;
            }
        }

        // 当发现修改了编号之后，需要校验新的编号是否已存在
        if(StringUtils.isNotBlank(mesOrder.getOrderNo()) && !mesOrder.getOrderNo().equals(mesOrders.get(0).getOrderNo())){
            MesOrder order1 = new MesOrder();
            order1.setOrderNoString(mesOrder.getOrderNo());
            List<MesOrder> orderList = mesOrderMapper.selectMesOrder(order1);
            if(orderList.size() > 0){
                return AjaxResult.error("订单编码[" + mesOrder.getOrderNo() + "]已存在，请修改后再保存");
            }
        }
        // 当发现修改了书刊编码之后，需要校验新的书刊编码是否已存在
        if(StringUtils.isNotBlank(mesOrder.getBookCode()) && !mesOrder.getBookCode().equals(mesOrders.get(0).getBookCode())){
            MesOrder order1 = new MesOrder();
            order1.setBookCode(mesOrder.getBookCode());
            List<MesOrder> mesOrders1 = mesOrderMapper.selectBookCode(order1);
          List<MesOrder> filterMesOrder=  mesOrders1.stream().filter(it -> !it.getPid().equals(mesOrder.getPid()))
                    .collect(Collectors.toList());
            if(filterMesOrder.size() > 0 ){
                return AjaxResult.error("书刊编码已存在，请修改后保存");
            }
        }
        // 修改订单信息
        mesOrderMapper.updateMesOrder(mesOrder);

        mesOrderCoverService.remove(new QueryWrapper<MesOrderCover>().lambda()
                .eq(MesOrderCover::getOrderId, mesOrder.getPid()));
        for (MesOrderCover mesOrderCover: mesOrder.getOrderCover()){
            mesOrderCover.setOrderId(String.valueOf(mesOrder.getPid()));
        }
        mesOrderCoverService.saveBatch(mesOrder.getOrderCover());

        // 修改品种信息
       /* if(orderBreedEdit != null && orderBreedEdit.size() > 0){
            //20240409   需要删除未在修改内容里面的数据
            mesOrderMapper.delOrderBreedNotId(orderBreedEdit);
            mesOrderMapper.updateOrderBreed(orderBreedEdit);
            }*/

        // 判断是否有删除的数据
        if(mesOrder.getBreedPidList() != null && mesOrder.getBreedPidList().size() > 0){
            // 1删除订单，2删除品种
            delMesOrderInfo(mesOrder, 2);
        }

        // 处理子信息 -- 新增
        if(breedMapAdd != null){
            // 获取品种最大编码
            MesOrderBreed breed = new MesOrderBreed();
            breed.setYearTime(year);
            breed.setMonthTime(month);
            List<MesOrderBreed> mesOrderBreeds = mesOrderMapper.selectMesOrderBreed(breed);
            // 获取最大的序号
            Integer maxBreen = 1;
            if(mesOrderBreeds.size() > 0){
                for (MesOrderBreed orderBreed : mesOrderBreeds) {
                    if(maxBreen.compareTo(orderBreed.getCodeNum()) < 0){
                        maxBreen = orderBreed.getCodeNum();
                    }
                }
            }
            maxBreen = maxBreen + 1;

            for (String breedId : breedMapAdd.keySet()) {
                // 获取品种编码
                String codeBreen = UtilsSetting.getCode(maxBreen, "DDPZ", date);
                // 获取品种信息
                MesOrderBreed orderBreed = breedMapAdd.get(breedId);
                orderBreed.setOrderId(mesOrder.getPid());
                orderBreed.setBreedNo(codeBreen);
                orderBreed.setCreateBy(username);
                orderBreed.setCreateTime(date);
                // 新增品种信息
                mesOrderMapper.insertMesOrderBreed(orderBreed);
                maxBreen ++;

                // 获取品种下对应的产品信息
//                if(productMapAdd != null){
//                    List<MesOrderProduct> orderProducts = productMapAdd.get(breedId);
//                    if(orderProducts != null && orderProducts.size() > 0){
//                        ArrayList<MesOrderProduct> products = new ArrayList<>();
//                        for (MesOrderProduct orderProduct : orderProducts) {
//                            orderProduct.setBreedPid(orderBreed.getPid());
//                            orderProduct.setCreateBy(username);
//                            orderProduct.setCreateTime(date);
//                            products.add(orderProduct);
//                        }
//                        //保存产品信息
//                        mesOrderMapper.insertMesOrderProduct(products);
//                    }
//                }
                // 获取品种下对应的内文信息
//                if(neiwenMapAdd != null){
//                    MesOrderNeiwen orderNeiwens = neiwenMapAdd.get(breedId);
//                    if(orderNeiwens != null && orderNeiwens.getBreedPid()  != null){
//                        orderNeiwens.setBreedPid(orderBreed.getPid());
//                        orderNeiwens.setCreateBy(username);
//                        orderNeiwens.setCreateTime(date);
//                        // 保存内文信息
//                        mesOrderMapper.insertMesOrderNeiwen(orderNeiwens);
//                    }
//                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 订单管理 -- 删除
     * @Date: 2024年1月9日
     * @Auth: 张恒
     * delType：1删除订单，2删除品种
     */
    @Transactional
    public AjaxResult delMesOrderInfo(MesOrder mesOrder, Integer delType){
        if(delType == 1){
            if(mesOrder.getPid() == null){
                return AjaxResult.error("未获取到删除的主键");
            }
            // 查询修改的数据
            MesOrder order = new MesOrder();
            order.setPid(mesOrder.getPid());
            List<MesOrder> mesOrders = mesOrderMapper.selectMesOrder(order);
            // 判断状态
            if(mesOrders.get(0).getStatus() != 1){
                return AjaxResult.error("只有未提交的订单才可删除");
            }
            // 查询关联的品种信息
            MesOrderBreed orderBreed = new MesOrderBreed();
            orderBreed.setOrderId(mesOrder.getPid());
            List<MesOrderBreed> mesOrderBreeds = mesOrderMapper.selectMesOrderBreed(orderBreed);
            if(mesOrderBreeds.size() > 0){
                ArrayList<String> longs = new ArrayList<>();
                mesOrderBreeds.forEach(e -> {
                    longs.add(e.getPid());
                });
                // 删除产品
                MesOrderProduct mesOrderProduct = new MesOrderProduct();
                mesOrderProduct.setBreedPidList(longs);
                mesOrderMapper.delMesOrderProduct(mesOrderProduct);
                // 删除内文
                MesOrderNeiwen mesOrderNeiwen = new MesOrderNeiwen();
                mesOrderNeiwen.setBreedPidList(longs);
                mesOrderMapper.delMesOrderNeiwen(mesOrderNeiwen);
                // 删除品种
                mesOrderMapper.delOrderBreed(orderBreed);
            }
            // 删除订单
            mesOrderMapper.delMesOrder(mesOrder);
             //删除封面
            mesOrderCoverService.remove(new QueryWrapper<MesOrderCover>().lambda()
                    .eq(MesOrderCover::getOrderId, mesOrder.getPid()));

        }else if(delType == 2){
            // 删除产品
            MesOrderProduct mesOrderProduct = new MesOrderProduct();
            mesOrderProduct.setBreedPidList(mesOrder.getBreedPidList());
            mesOrderMapper.delMesOrderProduct(mesOrderProduct);
            // 删除内文
            MesOrderNeiwen mesOrderNeiwen = new MesOrderNeiwen();
            mesOrderNeiwen.setBreedPidList(mesOrder.getBreedPidList());
            mesOrderMapper.delMesOrderNeiwen(mesOrderNeiwen);
            // 删除品种
            for (String aLong : mesOrder.getBreedPidList()) {
                MesOrderBreed orderBreed = new MesOrderBreed();
                orderBreed.setPid(aLong);
                mesOrderMapper.delOrderBreedByPid(orderBreed);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 订单管理 -- 导出
     * @Date: 2024年1月9日
     * @Auth: 张恒
     */
    public AjaxResult exportMesOrder(MesOrder mesOrder){
        // 查询数据
        List<MesOrder> mesOrders = mesOrderMapper.selectMesOrder(mesOrder);
        if(mesOrders.size() == 0){
            return AjaxResult.error("导出的数据为空");
        }
        //创建Workbook对象(excel的文档对象)
        SXSSFWorkbook swb = new SXSSFWorkbook(100);
        //建立新的sheet页
        SXSSFSheet sheet = swb.createSheet("订单信息导出");

        //标题样式
        CellStyle titleStyle = swb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        titleStyle.setFillForegroundColor((short) 67);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderBottom(BorderStyle.THIN); //下边框
        titleStyle.setBorderLeft(BorderStyle.THIN);//左边框
        titleStyle.setBorderTop(BorderStyle.THIN);//上边框
        titleStyle.setBorderRight(BorderStyle.THIN);//右边框
        // 设置字体
        Font font = swb.createFont();
        font.setBold(true);
        titleStyle.setFont(font);

        //单元格样式
        CellStyle cellStyle = swb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
        cellStyle.setBorderTop(BorderStyle.THIN);//上边框
        cellStyle.setBorderRight(BorderStyle.THIN);//右边框
        // 设置字体
        Font cellFont = swb.createFont();
        cellStyle.setFont(cellFont);

        //【3】设置单元格样式为会计专用
        CellStyle amtStyle = swb.createCellStyle();
        amtStyle.setDataFormat(swb.createDataFormat().getFormat("_* #,##0.00_ ;_* -#,##0.00_ ;_* \"-\"??_ ;_ @_ "));//会计专用格式
        amtStyle.setAlignment(HorizontalAlignment.RIGHT);//水平居左
        amtStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        amtStyle.setBorderBottom(BorderStyle.THIN); //下边框
        amtStyle.setBorderLeft(BorderStyle.THIN);//左边框
        amtStyle.setBorderTop(BorderStyle.THIN);//上边框
        amtStyle.setBorderRight(BorderStyle.THIN);//右边框
        Font amtFont = swb.createFont();
        amtStyle.setFont(amtFont);

        //【4】创建标题行
        SXSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("订单编码");
        row.createCell(1).setCellValue("书刊名称");
        row.createCell(2).setCellValue("科目");
        row.createCell(3).setCellValue("书号");
        row.createCell(4).setCellValue("定价");
        row.createCell(5).setCellValue("出版社");
        row.createCell(6).setCellValue("印刷数量（册）");
        row.createCell(7).setCellValue("打包方式");
        row.createCell(8).setCellValue("文件日期");
        row.createCell(9).setCellValue("备注");
        row.createCell(10).setCellValue("创建人");
        row.createCell(11).setCellValue("创建时间");
        row.createCell(12).setCellValue("状态");

        for (int i = 0; i <= 12; i++) {
            //设置表格列宽度为5000个字节
            sheet.setColumnWidth(i, 5000);
            //设置单元格样式
            row.getCell(i).setCellStyle(titleStyle);
        }

        // 查询字典
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("ems_workshop_subject_type"); // 科目
        List<SysDictData> dictData = sysDictDataMapper.selectDictDataList(sysDictData);
        Map<String, String> subjectTypeMap = dictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        sysDictData.setDictType("ems_order_pack_way"); // 打包方式
        List<SysDictData> dictData1 = sysDictDataMapper.selectDictDataList(sysDictData);
        Map<String, String> packWayMap = dictData1.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        sysDictData.setDictType("ems_order_status"); // 订单流转过程状态
        List<SysDictData> dictData2 = sysDictDataMapper.selectDictDataList(sysDictData);
        Map<String, String> statusWayMap = dictData2.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 创建数据
        int i = 1;
        for (MesOrder order : mesOrders) {
            // 科目
            StringBuffer stringBuffer = new StringBuffer();
            if(StringUtils.isNotBlank(order.getSubjectType())){
                String[] split = order.getSubjectType().split(",");
                for (int i1 = 0; i1 < split.length; i1++) {
                    stringBuffer.append(subjectTypeMap.get(split[i1]) + "；");
                }
            }
            row = sheet.createRow(i);
            row.createCell(0).setCellValue(order.getOrderNo());
            row.createCell(1).setCellValue(order.getOrderName());
            row.createCell(2).setCellValue(stringBuffer.toString());
            row.createCell(3).setCellValue(order.getBookNo());
            row.createCell(4).setCellValue(String.valueOf(order.getFixPrice()));
            row.createCell(5).setCellValue(order.getPublishingHouse());
            row.createCell(6).setCellValue(order.getPrintingCount());
            row.createCell(7).setCellValue(order.getPackWay() != null ? packWayMap.get(order.getPackWay()) : "");
            row.createCell(8).setCellValue(dateFormat.format(order.getFileDate()));
            row.createCell(9).setCellValue(order.getRemark());
            row.createCell(10).setCellValue(order.getCreateBy());
            row.createCell(11).setCellValue(dateFormat.format(order.getCreateTime()));
            row.createCell(12).setCellValue(order.getStatus() != null ? statusWayMap.get(order.getStatus()) : "");
            // 设置样式
            for (int j = 0; j <= 12; j++) {
                row.getCell(j).setCellStyle(cellStyle);
            }
            i++;
        }
        OutputStream out = null;
        try {
            // 创建文件名
            String filename = UUID.randomUUID().toString() + "订单信息导出.xlsx";
            String downloadPath = RuoYiConfig.getDownloadPath() + filename;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
            out = new FileOutputStream(downloadPath);
            swb.write(out);
            return AjaxResult.success(filename);
        } catch (Exception e) {
            throw new BaseException("导出Excel失败！" + e.getMessage());
        } finally {
            if (swb != null) {
                try {
                    swb.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
